package li.webqq.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import li.http.Response;
import li.webqq.model.Category;
import li.webqq.model.User;
import li.webqq.util.JsonUtil;
import li.webqq.util.MapUtil;

/**
 * @author 明伟
 */
public class GetUserFriends2Response extends Response {
    private List<User> users;

    private List<Category> categories;

    public List<User> getUsers() {
        if (null == this.users) {
            Map map = (Map) JsonUtil.fromJson(super.getBody());
            Map result = (Map) map.get("result");
            List<Map> friends = (List<Map>) result.get("friends");
            List<Map> marknames = (List<Map>) result.get("marknames");
            List<Map> vipinfo = (List<Map>) result.get("vipinfo");
            List<Map> info = (List<Map>) result.get("info");

            this.users = getFriends(friends);

            mergeUsers(this.users, marknames);
            mergeUsers(this.users, vipinfo);
            mergeUsers(this.users, info);
        }
        return this.users;
    }

    private void mergeUsers(List<User> users, List<Map> mapList) {
        for (User user : users) {
            if (null != user) {
                for (Map map : mapList) {
                    String uin = user.getUin();
                    String uin2 = map.get("uin") + "";
                    if (uin2.trim().isEmpty()) {
                        uin2 = map.get("u") + "";
                    }
                    if (null != uin && (uin.equals(uin2))) {
                        user = MapUtil.parse(user, map);
                    }
                }
            }
        }
    }

    public List<Category> getCategories() {
        if (null == this.categories) {
            this.categories = new ArrayList<Category>();
            Map map = (Map) JsonUtil.fromJson(super.getBody());
            Map result = (Map) map.get("result");
            List<Map> categories = (List<Map>) result.get("categories");
            for (Map each : categories) {
                this.categories.add(MapUtil.parse(Category.class, each));
            }
        }
        return this.categories;
    }

    private List<User> getFriends(List<Map> friends) {
        List<User> users = new ArrayList<User>();
        for (Map friend : friends) {
            User user = MapUtil.parse(User.class, friend);
            users.add(user);
        }
        return users;
    }

}